package org.lewis.demo.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.lewis.demo.entity.SysUser;
import org.lewis.demo.repo.UserRepository;
import org.lewis.demo.service.IUserService;
import org.springframework.data.domain.Example;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class UserServiceImpl implements IUserService {

    private final UserRepository userRepository;
    private final RedisTemplate<String, Object> redisTemplate;

    public UserServiceImpl(UserRepository userRepository, RedisTemplate redisTemplate) {
        this.userRepository = userRepository;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public List<SysUser> init(String prefix, Integer count) {
        List<SysUser> list = new ArrayList<>();
        for (int i = 1; i <= count; i++) {
            String name = String.format("%s-%d", prefix, i);
            list.add(new SysUser(name, new Date()));
        }
        return this.userRepository.saveAll(list);
    }

    @Override
    public List<SysUser> findAll(SysUser user) {
        Example<SysUser> example = Example.of(user);
        return this.userRepository.findAll(example);
    }

    @Override
    public SysUser findByName(String name) {
        if (this.redisTemplate.hasKey(name)) {
            log.info("Find {} from {}", name, "Redis");
            return (SysUser) this.redisTemplate.opsForValue().get(name);
        }

        log.info("Find {} from {}", name, "DB");
        SysUser user = this.userRepository.findByName(name);
        this.redisTemplate.opsForValue().set(name, user, 1, TimeUnit.MINUTES);
        return user;
    }

    @Override
    public Long cleanRedis() {
        Set<String> keys = this.redisTemplate.keys("*");
        return this.redisTemplate.delete(keys);
    }

}
